// This file is part of OpenTSDB.
// Copyright (C) 2017 TeleDB Development Group.
//
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 2.1 of the License, or (at your
// option) any later version.  This program is distributed in the hope that it
// will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser
// General Public License for more details.  You should have received a copy
// of the GNU Lesser General Public License along with this program.  If not,
// see <http://www.gnu.org/licenses/>.
package net.opentsdb.tsd.service;

import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import com.google.common.collect.Sets;
import com.stumbleupon.async.Deferred;
import net.opentsdb.core.TSDB;
import net.opentsdb.core.TsuidExchange;
import net.opentsdb.tsd.HttpQuery;
import net.opentsdb.tsd.controller.RemoveTagsController;
import net.opentsdb.uid.UniqueId;
import net.opentsdb.utils.JSON;
import net.opentsdb.utils.hbase.HbaseMetaUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 批量删除hbase时间线请求
 */
public class RemoveHbaseTsuidsService extends RpcServiceImpl{

    private static final Logger LOG = LoggerFactory.getLogger(RemoveHbaseTsuidsService.class);

    private HbaseMetaUtils utils;

    public RemoveHbaseTsuidsService(TSDB tsdb, HttpQuery query){
        super(tsdb, query);
        utils = tsdb.getHbaseWrapper().metaUtils;
    }

    @Override
    public void doPost() {
        doDelete();
    }

    @Override
    public void doDelete() {

        final List<String> tsuids = ((Map<String,List<String>>)params).get("tsuids");
        Set<String> metrics = Sets.newHashSet();

        if(tsuids == null){
            LOG.error("tsuid {} is null");
            putErrorResponse(false, "request error: tsuids is null");
            return;
        }

        LOG.debug("delete tsuid list size:{} in batch",tsuids.size());
        try{
            utils.deleteTsuids(tsuids);

            tsuids.forEach(tsuid -> metrics.add(TsuidExchange.getMetricFromTSUID(tsdb, UniqueId.stringToUid(tsuid))));

            // 清理tags信息
            metrics.forEach(metric -> {
                try{
                    (new RemoveTagsController(tsdb, metric)).handle();
                }catch (Exception e){
                    LOG.error("ttl Remove tags error",Joiner.on(",").join(metrics),e);
                }
            });
//            Deferred.group(delGroup).joinUninterruptibly();
            putResponse(true,"delete tsuid success");
        } catch (Exception e) {
            LOG.debug("delete tsuids error:",e);
            putErrorResponse(false, "delete tsuids: error");
        }
    }

    @Override
    public void checks() {
        if(!((Map<String,List<String>>)params).containsKey("tsuids")){
            LOG.info("error delete tsuid request");
            putErrorResponse(false,"error delete type request, ex:{tsuid:['001','002']}");
        }
    }

    @Override
    public Map<String,List<String>> doParse(){
        // json自动解析成linkedMap
        final String json = getQuery().getContent();
        return  JSON.parseToObject(json, Map.class);
    }
}
